<template>
  <div>
    <el-container>
      <el-header>
        <el-input
          placeholder="Enter Product ID"
          v-model="productId"
          @keyup.enter="searchByProductId"
          style="width: 300px; margin-right: 20px;"
        />
        <el-button type="primary" @click="searchByProductId">Search1</el-button>
        <el-button type="primary" @click="showAddProductDialog">Add Product</el-button>
      </el-header>
      <el-main>
        <el-row :gutter="20" style="margin-bottom: 20px;">
          <el-col :span="8">
            <el-select v-model="sortBy" placeholder="Sort By" @change="fetchProducts">
              <el-option label="Price" value="price"></el-option>
              <el-option label="Sold Count" value="count"></el-option>
              <el-option label="Modified Date" value="modifieddate"></el-option>
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-switch v-model="isAvailable" @change="fetchProducts" active-text="Available" inactive-text="Unavailable"></el-switch>
          </el-col>
          <el-col :span="8">
            <el-input-number v-model="categoryId" placeholder="Category ID" @change="fetchProducts"></el-input-number>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8" v-for="product in displayedProducts" :key="product.productID">
            <el-card :body-style="{ padding: '20px' }">
              <img :src="product.imageURL" alt="product image" style="width: 100%; margin-bottom: 20px;">
              <div style="margin-bottom: 10px;">
                <span>{{ product.name }}</span>
                <br>
                <span>Price: ${{ product.price }}</span>
                <br>
                <span>Sold: {{ product.count }}</span>
              </div>
              <el-button type="primary" @click="showPurchaseDialog(product)">Purchase</el-button>
              <el-button type="warning" @click="showRestockDialog(product)">Restock</el-button>
              <el-button @click="showMoreInfoDialog(product)">More Info</el-button>
            </el-card>
          </el-col>
        </el-row>
      </el-main>
    </el-container>

    <!-- Add Product Dialog -->
    <el-dialog v-model="addProductDialogVisible" title="Add Product" width="500">
      <el-form :model="newProductForm">
        <el-form-item label="Id" :label-width="formLabelWidth">
          <el-input v-model="newProductForm.id"></el-input>
        </el-form-item>
        <el-form-item label="Name" :label-width="formLabelWidth">
          <el-input v-model="newProductForm.name"></el-input>
        </el-form-item>
        <el-form-item label="Price" :label-width="formLabelWidth">
          <el-input-number v-model="newProductForm.price" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="Category" :label-width="formLabelWidth">
          <el-input v-model="newProductForm.category"></el-input>
        </el-form-item>
        <el-form-item label="Description" :label-width="formLabelWidth">
          <el-input v-model="newProductForm.description"></el-input>
        </el-form-item>
        <el-form-item label="Image URL" :label-width="formLabelWidth">
          <el-input v-model="newProductForm.imageURL"></el-input>
        </el-form-item>
        <el-form-item label="Stock Quantity" :label-width="formLabelWidth">
          <el-input-number v-model="newProductForm.stockQuantity" :min="0"></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addProductDialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="addProduct">Add</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- Stock Out Dialog -->
    <el-dialog v-model="purchaseDialogVisible" title="Stock Out" width="500">
      <el-form :model="purchaseForm">
        <el-form-item label="Quantity" :label-width="formLabelWidth">
          <el-input-number v-model="purchaseForm.quantity" :min="1"></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="purchaseDialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="purchaseProduct">Confirm</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- Restock Dialog -->
    <el-dialog v-model="restockDialogVisible" title="Restock" width="500">
      <el-form :model="restockForm">
        <el-form-item label="Quantity" :label-width="formLabelWidth">
          <el-input-number v-model="restockForm.quantity" :min="1"></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="restockDialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="restockProduct">Confirm</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- More Info Dialog -->
    <el-dialog v-model="moreInfoDialogVisible" title="More Info" width="500">
  <div v-if="currentProduct">
    <p><strong>ProductID:</strong> {{ currentProduct.productID }}</p>
    <el-input v-model="currentProduct.name" placeholder="Enter product name"></el-input>
    <el-input v-model="currentProduct.price" placeholder="Enter product price" type="number"></el-input>
    <el-input v-model="currentProduct.category" placeholder="Enter product category"></el-input>
    <el-input v-model="currentProduct.description" placeholder="Enter product description"></el-input>
    <el-input v-model="currentProduct.soldGoods" placeholder="Enter sold goods" type="number"></el-input>
    <el-input v-model="currentProduct.stockQuantity" placeholder="Enter stock quantity" type="number"></el-input>
  </div>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="moreInfoDialogVisible = false">Close</el-button>
      <el-button type="primary" @click="updateProduct">Update</el-button>
    </div>
  </template>
</el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';

export default {
  setup() {
    const products = ref([]);
    const displayedProducts = ref([]);
    const sortBy = ref('');
    const isAvailable = ref(true);
    const categoryId = ref(null);
    const productId = ref('');
    const purchaseDialogVisible = ref(false);
    const restockDialogVisible = ref(false);
    const moreInfoDialogVisible = ref(false);
    const addProductDialogVisible = ref(false);
    const purchaseForm = reactive({ quantity: 1 });
    const restockForm = reactive({ quantity: 1 });
    const newProductForm = reactive({
      name: '',
      price: 0,
      category: '',
      imageURL: '',
      stockQuantity: 0,
    });
    const currentProduct = ref(null);
    const formLabelWidth = '140px';

    const fetchProducts = async () => {
      const response = await axios.get('http://localhost:5220/api/Product', {
        params: {
          sortBy: sortBy.value,
          isAvailable: isAvailable.value,
          categoryId: categoryId.value,
        },
      });
      products.value = response.data;
      displayedProducts.value = products.value
        .sort((a, b) => a.productID - b.productID)
        .slice(0, 9);
    };

    const searchByProductId = async () => {
      if (!productId.value) {
        fetchProducts();
        return;
      }
      const response = await axios.get(`http://localhost:5220/api/Product/${productId.value}`);
      products.value = response.data ? [response.data] : [];
      displayedProducts.value = products.value;
    };

    const showPurchaseDialog = (product) => {
      currentProduct.value = product;
      purchaseDialogVisible.value = true;
    };

    const purchaseProduct = async () => {
      try {
        const response = await axios.post(`http://localhost:5220/api/Product/${currentProduct.value.productID}/sell`, {
          quantity: purchaseForm.quantity,
        });
        if (response.status === 200) {
          ElMessage.success('Purchase successful');
          purchaseDialogVisible.value = false;
          fetchProducts();
        }
      } catch (error) {
        ElMessage.error('Purchase failed');
      }
    };

    const showRestockDialog = (product) => {
      currentProduct.value = product;
      restockDialogVisible.value = true;
    };

    const restockProduct = async () => {
      try {
        const response = await axios.post(`http://localhost:5220/api/Product/${currentProduct.value.productID}/restock`, {
          quantity: restockForm.quantity,
        });
        if (response.status === 200) {
          ElMessage.success('Restock successful');
          restockDialogVisible.value = false;
          fetchProducts();
        }
      } catch (error) {
        ElMessage.error('Restock failed');
      }
    };

    const showMoreInfoDialog = (product) => {
      currentProduct.value = product;
      moreInfoDialogVisible.value = true;
    };

    const updateProduct = async () => {
  try {
    const response = await axios.put(`http://localhost:5220/api/Product/${currentProduct.productID}`, currentProduct);
    if (response.status === 200) {
      ElMessage.success('Product updated successfully');
      moreInfoDialogVisible.value = false;
      fetchProducts(); // 重新获取产品列表以更新显示
    }
  } catch (error) {
    ElMessage.error('Failed to update product');
    console.error(error.response ? error.response.data : error.message);
  }
};

    const showAddProductDialog = () => {
      addProductDialogVisible.value = true;
    };

    const addProduct = async () => {
      try {
        const product = {
          ProductID:newProductForm.id,
          Name: newProductForm.name,
          Price: newProductForm.price,
          Category: newProductForm.category,
          Description: newProductForm.category,     
          ImageURL: newProductForm.imageURL,
          SoldGoods: 0, // 初始售出数量
          StockQuantity: newProductForm.stockQuantity,
        };

        const response = await axios.post('http://localhost:5220/api/Product',  product );
        if (response.status === 200) {
          ElMessage.success('Product added successfully');
          addProductDialogVisible.value = false;
          fetchProducts(); // 重新获取产品列表
        }
      } catch (error) {
        ElMessage.error('Failed to add product');
        console.error(error.response ? error.response.data : error.message); // 打印错误信息以便调试
      }
    };

    return {
      products,
      displayedProducts,
      sortBy,
      isAvailable,
      categoryId,
      productId,
      purchaseDialogVisible,
      restockDialogVisible,
      moreInfoDialogVisible,
      addProductDialogVisible,
      purchaseForm,
      restockForm,
      newProductForm,
      currentProduct,
      formLabelWidth,
      fetchProducts,
      searchByProductId,
      showPurchaseDialog,
      purchaseProduct,
      showRestockDialog,
      restockProduct,
      showMoreInfoDialog,
      showAddProductDialog,
      addProduct,
    };
  },
};
</script>

<style scoped>
/* Add any custom styles here */
</style>